﻿using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Media;
using Avalonia.Styling;
using FluentAvalonia.Styling;

namespace DevManager.Pages;

public partial class SettingPage : UserControl
{
    public SettingPage()
    {
        InitializeComponent();
    }

    protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        
        ThemeComboBox.ItemsSource = new[] {"Light","Dark","System" };
        ThemeComboBox.SelectedItem = GetThemeVariant();
        
        FlowDirectionComboBox.ItemsSource = new[] { FlowDirection.LeftToRight, FlowDirection.RightToLeft };
        FlowDirectionComboBox.SelectedItem = GetFlowDirection(this);
    }


    private string GetThemeVariant()
    {
        var a = TopLevel.GetTopLevel(this);
        if (a == null) return "System";
        if (a.ActualThemeVariant == ThemeVariant.Default) return "System";
        return a.ActualThemeVariant == ThemeVariant.Dark ? "Dark" : "Light";
    }
    
    private ThemeVariant? GetThemeVariant(string value)
    {
        return value switch
        {
            "Light" => ThemeVariant.Light,
            "Dark" => ThemeVariant.Dark,
            _ => null
        };
    }

    private void ThemeChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (e.AddedItems.Count <= 0)
            return;
        var value = e.AddedItems[0]?.ToString();
        if(string.IsNullOrEmpty(value))return;
        if(Application.Current?.Styles[0] is not FluentAvaloniaTheme _faTheme)return;
        var newTheme = GetThemeVariant(value);
        var a = TopLevel.GetTopLevel(this);
        if(a?.ActualThemeVariant == newTheme)return;
        if (newTheme != null)
            Application.Current.RequestedThemeVariant = newTheme;
        _faTheme.PreferSystemTheme = value == "System";
    }


    private void FlowDirectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (e.AddedItems.Count <= 0)
            return;
        var value = e.AddedItems[0] is FlowDirection ? (FlowDirection)e.AddedItems[0]! : FlowDirection.LeftToRight;
        var lifetime = Application.Current?.ApplicationLifetime;
        if (lifetime is IClassicDesktopStyleApplicationLifetime cdl)
        {
            if (cdl.MainWindow!.FlowDirection == value)
                return;
            cdl.MainWindow.FlowDirection = value;
            return;
        }

        if (lifetime is not ISingleViewApplicationLifetime single) return;
        var mainWindow = TopLevel.GetTopLevel(single.MainView);
        if (mainWindow!.FlowDirection == value)
            return;
        mainWindow.FlowDirection = value;
    }
}